package com.lsm.sm.interceptor;

import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

//import com.lsm.sm.entity.ProxyUser;
import com.lsm.sm.entity.User;
import com.lsm.sm.service.UserService;
import com.lsm.sm.util.Const;
import com.lsm.sm.util.CookieUtil;
import com.lsm.sm.util.WebUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AutoLoginInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = 2353427764707501614L;
	
	@Resource
	private UserService userService;
	
	@Override
	public String intercept(ActionInvocation invocation ) throws Exception {
		
		User pu = WebUtil.getUser();
		if( pu == null ){
			Cookie cookie = CookieUtil.getCookie( Const.COOKIE_USER );
			
			if( cookie == null ){
				return "login";
			}
			
			String value = URLDecoder.decode( cookie.getValue(), "utf-8" );
			String[] usinf = value.split( "[:\\|]" );
			
			try{
				User user = new User();
				user.setProxyId( usinf[0] );
				user.setPassword( usinf[1] );
				userService.login( user );
			}catch( Exception e ){
				System.out.println( getClass().getName() + ": " + e.getMessage() );
				return "login";
			}
		}
		return invocation.invoke();
	}
}
